package bom.example.common.quarzt.config;

import bom.example.common.quarzt.domain.SysJob;
import bom.example.common.quarzt.service.SysJobService;
import org.mybatis.spring.annotation.MapperScan;
import org.quartz.spi.JobFactory;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;

import java.io.IOException;
import java.util.List;
import java.util.Properties;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/3/20 19:56
 * @since JDK 1.8
 *
 * 定时任务初始化配置
 */
@Configuration
@MapperScan("bom.example.common.quarzt.mapper")
public class QuarztInitConfig {

    private static final String QUARTZ_PROPERTIES_NAME = "/quartz.properties";

    @Autowired
    private SysJobService sysJobService;

    @Bean
    public JobFactory jobFactory(ApplicationContext applicationContext) {
        AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
        jobFactory.setApplicationContext(applicationContext);
        return  jobFactory;
    }

    class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {

        private transient AutowireCapableBeanFactory beanFactory;

        @Override
        public void setApplicationContext(final ApplicationContext context) {
            beanFactory = context.getAutowireCapableBeanFactory();
        }

        @Override
        protected Object createJobInstance(final TriggerFiredBundle bundle)
                throws Exception {
            final Object job = super.createJobInstance(bundle);
            beanFactory.autowireBean(job);
            return job;
        }
    }

    @Bean
    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource(QUARTZ_PROPERTIES_NAME));
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }

    @Autowired
    QuarztUtils quarztUtils;

    /**
     * 初始化
     */
    @Bean
    public void InitQuarztInit(){
        List<SysJob> sysJobs=sysJobService.list();
        sysJobs.forEach(e->{
           quarztUtils.addQuartz(e);
        });
    }
}
